/** * Create by mzq * Description: 数据回放弹框 * Date: 2025/2/18 08:45 *
Update: 2025/2/18 08:45 */

<template>
  <view class="data-playback-dialog">
    <MyDiaLog
      :width="800"
      :visible="visible"
      :titleName="titleName"
      @close="handleClose">
      <template>
        <view class="content-wrapper">

           <!-- 添加表格 -->
           <uni-table
            ref="table"
            :loading="loading"
            border
            stripe
            emptyText="暂无更多数据">
            <uni-tr>
              <uni-th width="100" align="center">姓名</uni-th>
              <uni-th width="80" align="center">性别</uni-th>
              <uni-th width="120" align="center">住院号</uni-th>
              <uni-th width="160" align="center">创建时间</uni-th>
              <uni-th width="120" align="center">操作</uni-th>
            </uni-tr>
            <uni-tr v-for="(item, index) in tableData" :key="index">
              <uni-td align="center">{{ item.name }}</uni-td>
              <uni-td align="center">{{ item.sex }}</uni-td>
              <uni-td align="center">{{ item.admissionNumber }}</uni-td>
              <uni-td align="center">{{ item.createData || item.createTime || '未知' }}</uni-td>
              <uni-td align="center">
                <view class="uni-group">
                  <text class="action-text" @click="handleView(item)">查看</text>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>

          <!-- 分页组件 -->
          <view class="pagination-wrapper">
            <uni-pagination
              class="custom-pagination"
              :total="total"
              :pageSize="pageSize"
              :current="currentPage"
              @change="handlePageChange"
              showIcon>
            </uni-pagination>
          </view>
        </view>
      </template>
    </MyDiaLog>
  </view>
</template>

<script>
import MyDiaLog from '@/components/MyDiaLog/MyDiaLog.vue'
import { readJsonFromFile, deleteById } from '@/utils/fileUtil'

export default {
  name: 'DataPlaybackDialog',
  components: {
    MyDiaLog,
  },
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      titleName: '数据回放',
      patientData: null,
      loading: false,
      tableData: [], // 表格数据
      originalData: [], // 存储原始数据
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示条数
      total: 0, // 总条数
      
      // 添加缓存
      dataLoaded: false, // 标记数据是否已加载
      patientCache: {}, // 患者数据缓存
    }
  },
  watch: {
    visible(newVal){
      this.getPatient();
    },

    value(newVal) {
      console.log("数据回放",newVal)
      this.visible = newVal

      if (newVal && !this.dataLoaded) {
        // 当弹框显示且数据未加载时，加载数据
    
      }
    }
  },
  methods: {
    getPatient(){
      if (this.loading || this.dataLoaded) return; // 如果正在加载或已加载，则不重复加载
      
      this.loading = true
      try {
        // 显示加载提示
        uni.showLoading({
          title: '加载数据...',
          mask: true
        });
        
        // 1. 首先读取患者ID文件
        const patientIdsFile = '/sdcard/test/patient_ids.json';
        const patientIdsData = readJsonFromFile(patientIdsFile) || [];
        
        // 将数据转换为数组格式
        const patientIds = Array.isArray(patientIdsData) ? patientIdsData : [patientIdsData];
        
        // 2. 读取每个患者的报告文件
        const patients = [];
        
        // 如果没有患者ID，尝试从旧的患者文件中读取
        if (patientIds.length === 0 || (patientIds.length === 1 && !patientIds[0].id)) {
          const patientsFile = '/sdcard/test/patient.json';
          const patientsData = readJsonFromFile(patientsFile) || [];
          
          if (Array.isArray(patientsData) && patientsData.length > 0) {
            // 过滤出有完整脑电数据的患者
            const validPatients = patientsData.filter(patient => {
              return patient && 
                     patient.id && 
                     patient.leftBrainImpedance && 
                     patient.rightBrainImpedance && 
                     patient.allBrainImpedance && 
                     patient.stabilityWholeBrain;
            });
            
            patients.push(...validPatients);
            console.log(`从旧文件中加载了 ${validPatients.length}/${patientsData.length} 个有效患者数据`);
          }
        } else {
          // 正常从患者ID文件中读取
          for (const patientIdObj of patientIds) {
            if (!patientIdObj || !patientIdObj.id) continue;
            
            const patientId = patientIdObj.id;
            
            // 检查缓存
            if (this.patientCache[patientId]) {
              // 验证缓存的数据是否包含必要的脑电数据字段
              const cachedData = this.patientCache[patientId];
              if (cachedData && 
                  cachedData.leftBrainImpedance && 
                  cachedData.rightBrainImpedance && 
                  cachedData.allBrainImpedance && 
                  cachedData.stabilityWholeBrain) {
                patients.push(cachedData);
              }
              continue;
            }
            
            const patientReportFile = `/sdcard/test/${patientId}.json`;
            const patientReport = readJsonFromFile(patientReportFile);
            
            if (patientReport) {
              // 如果是数组，取第一个元素
              const patientData = Array.isArray(patientReport) ? patientReport[0] : patientReport;
              
              // 检查是否有基本信息和必要的脑电数据
              if (patientData && 
                  patientData.id && 
                  patientData.leftBrainImpedance && 
                  patientData.rightBrainImpedance && 
                  patientData.allBrainImpedance && 
                  patientData.stabilityWholeBrain) {
                
                // 确保有日期字段
                if (!patientData.createData && patientData.createTime) {
                  patientData.createData = patientData.createTime;
                }
                
                // 缓存数据
                this.patientCache[patientId] = patientData;
                
                patients.push(patientData);
              } else {
                console.log(`患者 ${patientId} 数据不完整，缺少必要的脑电数据字段，从列表中排除`);
              }
            }
          }
        }
        
        // 按创建时间降序排序
        patients.sort((a, b) => {
          const dateA = new Date(a.createData || a.createTime || 0);
          const dateB = new Date(b.createData || b.createTime || 0);
          return dateB - dateA;
        });
        
        this.originalData = patients;
        this.total = patients.length;
        this.updateTableData();
        this.dataLoaded = true; // 标记数据已加载
        
        // 隐藏加载提示
        uni.hideLoading();
        
        // 如果没有有效数据，显示提示
        if (patients.length === 0) {
          uni.showToast({
            title: '没有找到有效的患者数据',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取患者数据失败:', error);
        this.originalData = [];
        this.tableData = [];
        this.total = 0;
        
        // 隐藏加载提示
        uni.hideLoading();
        
        // 显示错误提示
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      } finally {
        this.loading = false
      }
    },

    handleClose() {
      this.$emit('input', false)
      this.$emit('close')
      
      // 重置数据加载状态，以便下次打开时能够重新加载数据
      this.dataLoaded = false;
    },

    handlePageChange(e) {
      this.currentPage = e.current
      this.updateTableData()
    },

    updateTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.tableData = this.originalData.slice(start, end)
    },

    handleView(item) {
      console.log('查看：', item)
      try {
        // 直接使用患者报告文件中的数据
        if (item && item.id) {
          // 确保有监测数据，如果没有则提示
          if (!item.leftBrainImpedance || !item.rightBrainImpedance || !item.allBrainImpedance || !item.stabilityWholeBrain) {
            uni.showToast({
              title: '该患者脑电数据不完整',
              icon: 'none'
            });
            return;
          }
          
          // 触发父组件的回放事件
          this.$emit('playback', item)
          
          // 关闭弹框
          this.handleClose()
        } else {
          uni.showToast({
            title: '患者数据不完整',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('读取数据失败：', error)
        uni.showToast({
          title: '读取数据失败',
          icon: 'none'
        })
      }
    },

  },
  mounted() {
    // 不在挂载时加载数据，而是在组件显示时加载
    this.visible = this.value;
  },
  
  beforeDestroy() {
    // 组件销毁前清除所有状态
    this.dataLoaded = false;
    this.patientCache = {};
    
    // 确保关闭加载提示
    uni.hideLoading();
  },
}
</script>

<style scoped lang="scss">
.data-playback-dialog {
  .content-wrapper {
    padding: 20px;
    
    .patient-info {
      margin-bottom: 20px;
      
      .info-item {
        display: flex;
        margin-bottom: 10px;
        
        .label {
          width: 80px;
          font-weight: bold;
        }
      }
    }
  }

  .uni-group {
    display: flex;
    justify-content: center;
    gap: 15px;

    .action-text {
      font-size: 14px;
      color: #333;
      cursor: pointer;

      &:hover {
        color: #409eff;
      }

      &.delete-text {
        color: #f56c6c;
        
        &:hover {
          color: #f56c6c;
        }
      }
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    padding: 10px 0;

    /deep/ .custom-pagination {
      .uni-pagination__btn {
        min-width: 32px;
        height: 32px;
        line-height: 32px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 0;
        margin: 0 4px;
        text-align: center;
        display: inline-block;
        box-sizing: border-box;
        background: #fff;

        &:hover {
          color: #409eff;
          border-color: #409eff;
        }
      }

      .uni-pagination__num {
        margin: 0 8px;
      }

      .uni-pagination__num-tag {
        min-width: 32px;
        height: 32px;
        line-height: 32px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 0 4px;
        margin: 0 4px;
        text-align: center;
        display: inline-block;
        box-sizing: border-box;
        background: #fff;
        cursor: pointer;

        &:hover {
          color: #409eff;
          border-color: #409eff;
        }

        &.page--active {
          background-color: #409eff !important;
          color: #fff !important;
          border-color: #409eff !important;
          font-weight: bold;

          &:hover {
            color: #fff !important;
          }
        }
      }
    }
  }
}
</style>
